(function(window, undefined) {
	
	var _currentZoomIdx_ = undefined ;
	var setCurrentZoomIdx = function(currentZoomIdx) {_currentZoomIdx_ = currentZoomIdx ;} ;
	var getCurrentZoomIdx = function() {return _currentZoomIdx_ ;} ;
	
	var _defaultZoomIdx_ = undefined ;
	var setDefaultZoomIdx = function(defaultZoomIdx) {_defaultZoomIdx_ = defaultZoomIdx ;} ;
	var getDefaultZoomIdx = function() {return _defaultZoomIdx_ ;} ;
	
	var _zoomPool_ = [0.25, 0.4, 0.55, 0.7, 0.85, 1, 1.25, 1.5, 2.0, 2.5, 3.0] ;
	var getZoomPool = function() {return _zoomPool_ ;} ;
	
	var _floorCount_ = -1;
	var getFloorCount = function() {return _floorCount_ ; };
	var setFloorCount = function(floorCount) {
		_floorCount_ = floorCount ;
	};
	
	var _numOfFloor_ = undefined ;
	var setNumOfFloor = function(numOfFloor) {_numOfFloor_ = numOfFloor ;} ;
	var getNumOfFloor = function() {return _numOfFloor_ ;} ;
	
	var _originalViewBox_ = {width : undefined, height : undefined} ;
	var setOriginalViewBox = function(width, height) {_originalViewBox_.width = width ; _originalViewBox_.height = height ;} ;
	var getOriginalViewBox = function() {return _originalViewBox_ ;} ;
	
	var _floorOnOffInfo_ = {onLight : undefined, onPower : undefined, floorId : undefined} ;
	var setFloorOnOffInfo = function(onLight, onPower, floorId) {
		_floorOnOffInfo_.onLight = onLight ;
		_floorOnOffInfo_.onPower = onPower ;
		_floorOnOffInfo_.floorId = floorId ;
	} ;
	var getFloorOnOffInfo = function() {
		return _floorOnOffInfo_ ;
	} ;
	
	var _svgContentPos_ = {x : undefined, y : undefined} ;
	var setSvgContentPos = function(x, y) {_svgContentPos_.x = x ; _svgContentPos_.y = y ;} ;
	var getSvgContentPos = function() {return _svgContentPos_ ;} ;
	
	var _canvas_ = undefined;
	var getCanvas = function() {return _canvas_ ;};
	
	var _workareaIScroll_ = new iScroll('workarea', {
		hScrollbar: false,
		vScrollbar: false,
		hScroll:true,
		vScroll:true,
		hideScrollbar: true,
		fadeScrollbar: true,
		bounce : false,
		momentum : false,
		lockDirection : false
	}) ;
	var getWorkAreaIScroll = function() {return _workareaIScroll_ ;} ;
	
	var _extensions_ = [];
	var getExtension = function(id) {
		
		var extension = undefined;
		for (var i = 0, iLen = _extensions_.length ; i < iLen ; i++) {
			if (_extensions_[i].id == id) {
				extension = _extensions_[i].extension;
				break;
			}
		}
		
		return extension; 
	};
	var addExtension = function(id, extension) {
		_extensions_.push({id:id, extension:extension});
	};
	
	var execExtension = function(/*eventType, event, parameter*/) {
		var currentExtension = getExtension(currentWork());
		return currentExtension.action.apply(currentExtension, arguments);
	};
	
	var _work_ = 'roomselect';
	var getDefaultWork = function() {
		return 'roomselect';
	};
	var currentWork = function() {
		
		return _work_; 
	};
	var changeWork = function(work) {
		if (_work_ == work) {
			return;
		}
		
		if (work == "UndoButton" || work == "RedoButton") {
			var ext = floorplan.editor.getExtension(work);
			ext[work.toLowerCase().replace("button", "")].call(ext);
			floorplan.editor.getExtension("ResizeRoom").selectedRoom = null;
			return;
		}
		
		//when change work, set room data and position
		if (_work_ != "roomselect" && _work_ != "ResizeRoom") {
			var extension = floorplan.editor.getExtension(_work_);
			
			if (extension.onWorkEnd instanceof Function) {
				extension.onWorkEnd.call(extension);
			}
			floorplan.editor.getExtension("ResizeRoom").selectedRoom = null;
		}
		
		if (work == "roomselect") {
			floorplan.editor.getCanvas().displayRoomInfo();
		}
		
		_work_ = work;
		console.log("[current work] " + _work_);
	};
	
	var initWork = function() {
		var extension = floorplan.editor.getExtension(_work_);
		if (extension && extension.onWorkEnd && extension.onWorkEnd instanceof Function) {
			extension.onWorkEnd.call(extension);
		}
		
		floorplan.editor.getExtension("ResizeRoom").removeGuideLine();
		floorplan.editor.getExtension("ResizeRoom").selectedRoom = null;
		floorplan.editor.getExtension("ResizeRoom").showRoomInfoPopup(false);
		_work_ = getDefaultWork();
	};
	
	var timeoutId = null;
	var showMessage = function(message) {
//		jQuery("#message > p").html(message);
//		jQuery("#message").show();
//		
//		if (timeoutId) {
//			clearTimeout(timeoutId);
//		}
//		timeoutId = setTimeout(function() {
//			jQuery("#message").hide();
//		}, 2000);
	};
		
	var _mode_ = undefined;
	var currentMode = function() {
		
		return _mode_;
	};
	var changeMode = function(mode) {
	
		_mode_ = mode;
		switch(mode) {
		default :
		case 'viewer' :
			_viewerMode_();
			break;
		case 'editor' :
			_editorMode_();
			break;
		}
	};
	
	var _viewerMode_ = function() {
		if (isPhone()) {
			getJQfloorplanWrap().find('.floorplan-guide-floorbox').css({
				'height' : '100px'
			});
		
			getJQfloorplanWrap().find('.editor').css({
				'top' : '100px',
				'right' : '',
				'bottom' : '320px'
			});
		} else {
			getJQfloorplanWrap().find('.floorplan-guide-floorbox').css({
				'height' : '60px'
			});
		
			getJQfloorplanWrap().find('.editor').css({
				'top' : '60px',
				'right' : '360px',
				'bottom' : '',
				//'left' : '200px'
			});
			
//			$(".floorplan-room").append("<div class='shadow'></div>");
		};
		
		jQuery("svg#canvasGrid").hide() ;
		$(".navigation h2").html("<span>MY HOME</span><span>Floor</span>");
		getJQfloorplanWrap().find('.aside').hide();
		
		getJQfloorplanWrap().find('.editor').css("visibility", "visible") ;
		getJQfloorplanWrap().find('.floorplan-room').show() ;
		getJQfloorplanWrap().find('.floorplan').css("visibility", "hidden") ;
		
		getJQfloorplanWrap().find('footer').html(
				'<button type="button">Edit</button>'
		+		'<button type="button" class="btn dashboard"><div class="icon"></div>dashboard</button>'	
		);
	
		var zoomPickerHtml = 	'<div class="zoom-picker">' +
									'<button type="button" class="default">' +
										'<div class="icon plus"></div>+' +
									'</button>' +
									'<button type="button" class="default">' + 
										'<div class="icon minus"></div>-' +
									'</button>' +
								'</div>' ;
		
		if(getJQfloorplanWrap().find('.editor').find(".zoom-picker").length > 0) {
			getJQfloorplanWrap().find('.editor').find(".zoom-picker").remove() ;
		}
		
		getJQfloorplanWrap().find('.editor').append(zoomPickerHtml) ;
		
		_jQfloorplanWrap_.find('.editor .zoom-picker .icon.plus').parent().unbind('click').bind('click', function() {
			changeZoom("plus") ;
		});
		
		_jQfloorplanWrap_.find('.editor .zoom-picker .icon.minus').parent().unbind('click').bind('click', function() {
			changeZoom("minus") ;
		});		
		
		_jQfloorplanWrap_.find('footer button:eq(0)').bind('click', function() {
			changeMode('editor');
		});
			
		floorplan.datasource.DataSource.getInstance().selectFloors({
			success : function(returnData) {
				getJQfloorplanWrap().find('.floorplan-guide-floorbox .button').empty();
				
				var floors = returnData.floors,
					length = floors.length ;
				
				getJQfloorplanWrap().find('.floorplan-guide-floorbox .button').append(
					jQuery('<button type="button">Home</button>').bind('click', function() {
						$(".navigation h2 span:last").html("HOME");
						//jQuery(".floorplan-guide-floorbox .button").hide() ;
						$('.floorplan-guide.floorH dd:eq(0)').text('Home') ;
						
						var prevFloorId = $(".floorplan-guide-floorbox div.button button.selected").attr("data-floorid");
						$('.floorplan-guide-floorbox .button button:gt(0)').removeClass("selected") ;
						$('.floorplan-guide-floorbox .button button:gt(0)').siblings().removeClass("selected") ;
						jQuery(this).addClass("selected").prependTo($(".floorplan-guide-floorbox div.button"));
						$('.editor').css("visibility", "hidden") ;
						$('.floorplan').css("visibility", "visible") ;
						$('.floorplan-room').css('z-index', 7) ;
						jQuery("#maparea").hide() ;
						getWorkAreaIScroll().disable() ;
						setFloorColor();
						
						jQuery(".floorplan-room p:eq(0)").text('Floor' + ((getNumOfFloor() != undefined && getNumOfFloor() != null && !isNaN(getNumOfFloor()) && getNumOfFloor() > 1) ? (' ' + getFloorCount()) : '')) ;
						jQuery(".floorplan-room button").text("Go to FLOOR") ;
//						window.flooridid = jQuery(".floorplan-home .home-floor .selected").attr("data-floorid") ;
						window.flooridid = prevFloorId;
						
						var roomList = jQuery("path[data-type=room]"),
							len = roomList.length,
							onPower = false,
							onLight = false ;
							//floorId = jQuery("path[data-type=floor]").attr("id") ;
						
						for(var i = 0 ; i < len ; i++) {
							var roomId = roomList.filter(":eq(" + i + ")").attr("id"),
								roomInfo = getCanvas().getRoomDataFromElement(roomId) ;
							
							if(roomInfo.poweron == "true") {
								onPower = true ;
							}
							
							if(roomInfo.lighton == "true") {
								onLight = true ;
							}
						}
						
						setFloorOnOffInfo(onLight, onPower, getFloorCount()) ;
						
						$('.floorplan-room').find('.button.lights img').attr('src', '/smarthome/images/tablet/room_lights_' + ((getFloorOnOffInfo().onLight == true) ? 'on' : 'off') + '.png') ;
						if (getFloorOnOffInfo().onLight) {
							jQuery(".home-floor dl[data-floorid=" + prevFloorId + "]").addClass("lighton");
						} else {
							jQuery(".home-floor dl[data-floorid=" + prevFloorId + "]").removeClass("lighton");
						} 
						
						if(getFloorOnOffInfo().onPower) {
							jQuery(".home-floor dl.selected .icon.alert").removeClass("on").removeClass("off").addClass("on") ;
						} else {
							jQuery(".home-floor dl.selected .icon.alert").removeClass("on").removeClass("off").addClass("off") ;
						}
						
						$('.floorplan-room').find('.button.power img').attr('src', '/smarthome/images/tablet/room_power_' + ((getFloorOnOffInfo().onPower == true) ? 'on' : 'off') + '.png') ;			
						$('.floorplan-room').find('.button.lights img').unbind("click").bind("click", function(event) {
							var onOffInfo = getFloorOnOffInfo() ;
							
							if (jQuery(this).attr('src') == '/smarthome/images/tablet/room_lights_on.png') {
								jQuery(this).attr('src', '/smarthome/images/tablet/room_lights_off.png') ;
								onOffInfo.onLight = "false" ;
								
								jQuery(".home-floor dl.selected").removeClass("lighton");
							} else {
								jQuery(this).attr('src', '/smarthome/images/tablet/room_lights_on.png') ;
								onOffInfo.onLight = "true" ;
								
								jQuery(".home-floor dl.selected").addClass("lighton");
							}
							
							floorplan.datasource.DataSource.getInstance().updateFloorLightPower({
								data : {
									floorId : onOffInfo.floorId,
									lightOn : onOffInfo.onLight,
									powerOn : onOffInfo.onPower.toString()
								}
							});
						}) ;
						
						$('.floorplan-room').find('.button.power img').unbind("click").bind("click", function(event) {
							var onOffInfo = getFloorOnOffInfo() ;
							
							if (jQuery(this).attr('src') == '/smarthome/images/tablet/room_power_on.png') {
								jQuery(this).attr('src', '/smarthome/images/tablet/room_power_off.png') ;
								onOffInfo.onPower = "false" ;
								jQuery(".home-floor dl.selected .icon.alert").removeClass("on").removeClass("off").addClass("off") ;
							} else {
								jQuery(this).attr('src', '/smarthome/images/tablet/room_power_on.png') ;
								onOffInfo.onPower = "true" ;
								jQuery(".home-floor dl.selected .icon.alert").removeClass("on").removeClass("off").addClass("on") ;
							}
							
							floorplan.datasource.DataSource.getInstance().updateFloorLightPower({
								data : {
									floorId : onOffInfo.floorId,
									lightOn : onOffInfo.onLight.toString(),
									powerOn : onOffInfo.onPower
								}
							});
						}) ;
						
						$(".floorplan-room button").unbind("click").bind("click", function(event) {	//go to floor							
							floorplan.datasource.DataSource.getInstance().selectFloor(window.flooridid, {
								success : function(returnData) {
									floorplan.editor.getCanvas().importFloor(returnData.svg) ;
					
									jQuery(".floorplan-room button").text("Go to ROOM") ;
									jQuery(".floorplan-guide-floorbox .button").show() ;									
									jQuery(".floorplan-guide-floorbox button").removeClass("selected");
									jQuery(".floorplan-guide-floorbox [data-floorid=" + window.flooridid + "]").addClass("selected") ;
					
									$('.floorplan-guide.floorH dd:eq(0)').text('Floor' + ((getNumOfFloor() != undefined && getNumOfFloor() != null && !isNaN(getNumOfFloor()) && getNumOfFloor() > 1) ? (' ' + getFloorCount()) : ''));
									
									var jQfloorChildren = getJQfloorplanWrap().find('.editor .floor').children();
									jQfloorChildren.filter('.selected').removeClass('selected');
									jQfloorChildren.filter(':eq(' + (getFloorCount() - 1) + ')').addClass('selected');
									if (isMobile()) {
										$(".floorplan-guide-floorbox div.button").prepend($(".floorplan-guide-floorbox div.button button.selected"));
									}
									goToCenterThroughBBox(jQuery("path[data-type=floor]"), getTightZoomForFloor()) ;
									getJQfloorplanWrap().find(".floorplan").css("visibility", "hidden") ;
									jQuery('.editor').css("visibility", "visible") ;
									floorplan.editor.getCanvas().displayRoomInfoBox();
									floorplan.editor.getCanvas().drawRoomLightOfView();
								}
							});	
						}) ;
						
						/* 2012.11.08, 수정 사항 */
						if (!isMobile()) {
							var homeCoverHeight = jQuery(".floorplan-home-cover").outerHeight(true),
								homeHeight = jQuery(".home-ground").outerHeight(true) + jQuery(".home-roof").outerHeight(true) + jQuery(".home-floor").outerHeight(true),
								bottom = (homeCoverHeight - homeHeight) / 2;
							
							jQuery(".floorplan-home").css("bottom", bottom + 43);
						} else {
							var homeCoverHeight = jQuery(".floorplan-home-cover").outerHeight(true) - jQuery("header").outerHeight(true) - jQuery(".navigation").outerHeight(true) - jQuery(".floorplan-guide-floorbox").outerHeight(true),
								homeHeight = jQuery(".home-ground").outerHeight(true) + jQuery(".home-roof").outerHeight(true) + jQuery(".home-floor").outerHeight(true),
								bottom = (homeCoverHeight - homeHeight) / 2;
							
							jQuery(".floorplan-home").css("bottom", bottom);
						}
					})
				);
				
				if (isMobile()) {
					for (var i = 0 ; i < length ; i++) {
						if (i==(getFloorCount()-1)) {
							getJQfloorplanWrap().find('.floorplan-guide-floorbox .button').prepend('<button data-floorId="' + floors[i].floor_id + '" class="selected">Floor ' + (i + 1) + '</span>');
						} else {
							getJQfloorplanWrap().find('.floorplan-guide-floorbox .button').append('<button data-floorId="' + floors[i].floor_id + '">Floor ' + (i + 1) + '</span>');
						}
					}
				} else {
					for (var i = 0 ; i < length ; i++) {
						getJQfloorplanWrap().find('.floorplan-guide-floorbox .button').append('<button data-floorId="' + floors[i].floor_id + '" ' + ((i==(getFloorCount()-1)) ? 'class="selected"' : '') + '>Floor ' + (i + 1) + '</span>');
					}
				}
				
				if (getJQfloorplanWrap().find(".floorplan-guide-floorbox .button button").size() == 2) {
					getJQfloorplanWrap().find(".floorplan-guide-floorbox .button button.selected").html("Floor");
				}
				
				$('.floorplan-guide-floorbox .button button[data-floorId]').unbind('click').bind('click', function() {
					
					if (jQuery(this).hasClass('selected')) {
						return;
					}
					
					var floorName = 'Floor' + ((getNumOfFloor() != undefined && getNumOfFloor() != null && !isNaN(getNumOfFloor()) && getNumOfFloor() > 1) ? (' ' + getFloorCount()) : '');
					
					$(".navigation h2 span:last").html(floorName);
					
					jQuery(".floorplan-room button").text("Go to ROOM") ;
					$('.floorplan-guide.floorH dd:eq(0)').text(floorName);
					jQuery(".floorplan-guide-floorbox .button").show() ;	
					getWorkAreaIScroll().enable() ;
					getJQfloorplanWrap().find(".floorplan").css("visibility", "hidden") ;
					jQuery('.editor').css("visibility", "visible") ;					
					
					getJQfloorplanWrap().find(".floorplan-guide-floorbox .button button:eq(0)").removeClass("selected") ;
					jQuery(this).siblings().removeClass('selected');
					jQuery(this).addClass('selected');
					if (isMobile()) {
						jQuery(".floorplan-guide-floorbox div.button").prepend(this);
					}
					
					setFloorCount(jQuery(this).index() + 1); 
					
					floorplan.datasource.DataSource.getInstance().selectFloor(jQuery(this).attr('data-floorId'), {
						success : function(returnData) {
							floorplan.editor.getCanvas().importFloor(returnData.svg);
							goToCenterThroughBBox(jQuery("path[data-type=floor]"), getTightZoomForFloor()) ;
							floorplan.editor.getCanvas().displayRoomInfo();
							
							var floorList = jQuery(".home-floor dl") ;
							floorList.removeClass().addClass("default").each(function() {
								var floor = jQuery(this).attr("data-floorcount") ;
								if(floor == getFloorCount()) {
									jQuery(this).addClass("selected") ;
								}
							}) ;
							floorplan.editor.getCanvas().displayRoomInfoBox();
							floorplan.editor.getCanvas().drawRoomLightOfView();
						}
					});
				});
				
				floorplan.editor.getCanvas().drawRoomLightOfView();
			}
		});
		
		if (isMobile()) {
			getJQfloorplanWrap().find('.floorplan-guide-floorbox .button').removeClass('open').addClass('close').unbind('click').bind('click', function() {
				if (jQuery(this).hasClass('close')) {
					jQuery(this).removeClass('close').addClass('open');
					
					jQuery(this).children().css('display', 'block');
				} else {
					jQuery(this).removeClass('open').addClass('close');
					jQuery(this).children().css('display', '');
				}
			});
			
			getJQfloorplanWrap().find('.floorplan-guide-floorbox .button').children().bind('click', function() {
					
				if (jQuery(this).parent().hasClass('close')) {
					return;
				}
						
				var jQsiblings = jQuery(this).siblings();
				
				if (jQuery(this).index() == jQsiblings.add(this).length - 1) {
					return;
				}
				
				Array.prototype.sort.call(jQsiblings, function(a, b) {
					return parseInt(jQuery(b).text()) - parseInt(jQuery(a).text());
				});
				
				jQuery(this).parent().prepend(this);
				jQuery(this).parent().append(jQsiblings);
			});
		}
				
		_jQfloorplanWrap_.find('footer button.btn.dashboard').bind('click', function() {
			getJQfloorplanWrap().find(".floorplan, .editor").css("visibility", "hidden") ;
			getJQfloorplanWrap().find('.floorplan-room').css('display', 'none');
			jQuery('.board').show();
			jQuery(".floorplan-wrap").css("visibility", "hidden").hide() ;
			$(".navigation h2").text("MY BOARD");
			shDashBoard.iScrollResize();
		});
		
		initWork();
		floorplan.editor.getCanvas().drawRoomLightOfView();
		$('.floorplan-guide-floorbox').show();
		getExtension("MiniMap").getMiniMap().setMiniMapInfo() ;
		getWorkAreaIScroll().enable() ;
		jQuery(".floorplan-guide-floorbox .button").show() ;
		
		if (document.querySelector("svg#svgcontent > g").childNodes.length > 0) {
			zoom = goToCenterThroughBBox(jQuery("path[data-type=floor]"), getTightZoomForFloor()) ;	
			floorplan.editor.getCanvas().displayRoomInfoBox();
			floorplan.editor.getCanvas().drawRoomLightOfView();
			jQuery("footer .zoom-picker").show() ;
		}
	};
	
	var _editorMode_ = function() {
		var workAreaIScroll = getWorkAreaIScroll() ;
		workAreaIScroll.enable() ;

		jQuery("g#clipPath").remove();
		
		jQuery("svg#canvasGrid").show() ;
		getJQfloorplanWrap().find('.editor').css({
			'top' : '',
			'right' : '',
			'bottom' : ''
		});
		
		getJQfloorplanWrap().find(".floorplan").css("visibility", "hidden") ;
		getJQfloorplanWrap().find('.floorplan-room').css('display', 'none');
		$(".navigation h2").html("<span>MY HOME</span><span>EDIT</span>");
		getJQfloorplanWrap().find('.aside').show();
		getJQfloorplanWrap().find('.editor').css('visibility', 'visible');
		
		getExtension("MiniMap").getMiniMap().setMiniMapInfo() ;
		
		getJQfloorplanWrap().find('footer').html(
				'<button type="button" class="done">Done</button>'
		+		'<button type="button" class="cancel">Cancel</button>'	
		);
		
		_jQfloorplanWrap_.find('footer button:eq(0)').bind('click', function() {
			floorplan.datasource.DataSource.getInstance().updateFloor(jQuery('.floorplan-guide-floorbox div.button button.selected').attr('data-floorId'), {
				data : {
					svg : floorplan.editor.getCanvas().exportFloor()
				},
				success : function(result) {
					shMenu.drawWrapper();
					shMenu.getMenuData();
					drawFloorplanView();
					/*checkReturnPage();
					floorplan.editor.getCanvas().lastSvgString = result.svg;
					floorplan.editor.clearFloor();
					_jQfloorplanWrap_.find('.floorplan-scale dd:eq(1)').trigger('click');*/
				}
			});
		});
		
		_jQfloorplanWrap_.find('footer button:eq(1)').bind('click', function() {
			drawFloorplanView();
		});
		
		var checkReturnPage = function() {
			var url = window.location.pathname,
				search = window.location.search;
			
			if (url.indexOf("/floorplan/edit/") != -1) {
				var nextUrl = "";
				if (search.indexOf("type=wizard") != -1) {
					nextUrl = "/smarthome/html/setup.html#preview";
				} else if (search.indexOf("type=dbmanager") != -1) {
					nextUrl = "/smarthome/floorDBManager";
				}
				
				location.href = nextUrl;
				return;
			} else {
				changeMode("viewer");
			}
		};
		
		var drawFloorplanView = function() {
			floorplan.datasource.DataSource.getInstance().selectFloors({
				success : function(returnData) {
					var floors = returnData.floors;
					
					if (floors == null || !(floors instanceof Array) || floors.length < 1) {
						return;
					}
					
					floorplan.datasource.DataSource.getInstance().selectFloor(floors[((getFloorCount() != undefined && getFloorCount() != null &&  !isNaN(getFloorCount()) && getFloorCount() > 0) ? getFloorCount() - 1 : ((function(){setFloorCount(1);return 1 ;}())) - 1)].floor_id, {
						success : function(returnData) {
							checkReturnPage();
							floorplan.editor.getCanvas().importFloor(returnData.svg);
							goToCenterThroughBBox(jQuery("path[data-type=floor]"), getTightZoomForFloor(true)) ;	
							floorplan.editor.getCanvas().displayRoomInfoBox();
							floorplan.editor.getCanvas().drawRoomLightOfView();
							_jQfloorplanWrap_.find('.floorplan-scale dd:eq(1)').trigger('click');
						}
					});
				}
			});
		};
		
		var zoomPickerHtml = 	'<div class="zoom-picker">' +
									'<button type="button" class="default">' +
										'<div class="icon plus"></div>+' +
									'</button>' +
									'<button type="button" class="default">' + 
										'<div class="icon minus"></div>-' +
									'</button>' +
								'</div>' ;

		getJQfloorplanWrap().find('.editor').append(zoomPickerHtml) ;
		
		_jQfloorplanWrap_.find('.editor .zoom-picker .icon.plus').parent().unbind('click').bind('click', function() {
			changeZoom("plus") ;
			
			if(floorplan.editor.getExtension("ResizeRoom").selectedRoom != null) {
				moveTobBoxCenter(jQuery(floorplan.editor.getExtension("ResizeRoom").selectedRoom), getCanvas().getZoom()) ;
			}
		});
		
		_jQfloorplanWrap_.find('.editor .zoom-picker .icon.minus').parent().unbind('click').bind('click', function() {
			changeZoom("minus") ;
			
			if(floorplan.editor.getExtension("ResizeRoom").selectedRoom != null) {
				moveTobBoxCenter(jQuery(floorplan.editor.getExtension("ResizeRoom").selectedRoom), getCanvas().getZoom()) ;
			}
		});
		
		$(".zoom-picker").attr("style", "top:" + String(parseInt($(".zoom-picker").css("top").replace("px", "")) - $(".floorplan-guide-floorbox").outerHeight(true)) + "px;");
		
		$('.floorplan-guide-floorbox').hide();
		floorplan.editor.getCanvas().unDrawRoomInfo();
		
		goToCenterThroughBBox(jQuery("path[data-type=floor]"), getTightZoomForFloor());
	};
	
	

	var clearFloor = function(callback) {
		
		var svgString = floorplan.editor.getCanvas().lastSvgString;
		if(svgString != null) {
			floorplan.editor.getCanvas().importFloor(floorplan.editor.getCanvas().lastSvgString);
			changeMode("viewer");
		}
	};
	
	
	/**
	 * Canvas의 크기를 조정한다.
	 */
	var updateCanvas = function(center, new_ctr) {
		var svgCanvas = getCanvas();
		var workarea = jQuery("#workarea");
		var w = workarea.width(), h = workarea.height();
		var w_orig = w, h_orig = h;
		var zoom = svgCanvas.getZoom();
		var w_area = workarea;
		var cnvs = $("#svgcanvas");
		
		//contentW, contentH 설정
		getCanvas().setResolution(w, h);
		
		var multi = curConfig.canvas_expansion;
		w = Math.max(w_orig, svgCanvas.contentW * zoom * multi);
		h = Math.max(h_orig, svgCanvas.contentH * zoom * multi);
		
		if(w == w_orig && h == h_orig) {
			workarea.css('overflow','hidden');
		} else {
			workarea.css('overflow','hidden');
		}

		cnvs.width(w).height(h);

		var offset = svgCanvas.updateCanvas(w, h);
		var scroll_x = w/2 - w_orig/2;
		var scroll_y = h/2 - h_orig/2;
		if(center) {
			// Go to top-left for larger documents
			if(svgCanvas.contentW > w_area.width()) {
				// Top-left
				workarea[0].scrollLeft = offset.x - 10;
				workarea[0].scrollTop = offset.y - 10;
			} else {
				// Center
				w_area[0].scrollLeft = scroll_x;
				w_area[0].scrollTop = scroll_y;
			}
		} else {
			w_area[0].scrollLeft = 0;
			w_area[0].scrollTop = 0;
		}

	};	
	
	var curConfig = {
			/*
			mode : 'editor', 'viewer'
			work : 'default', 'select', 'addRoom'... 
			*/
	};
	
	var _jQfloorplanWrap_ = undefined;
	var getJQfloorplanWrap = function() {
		return _jQfloorplanWrap_; 
	};
	
	var init = function(config) {
		_jQfloorplanWrap_ = jQuery('.floorplan-wrap');
		
		var config = {
				mode : 'viewer',
				canvas_expansion: 1,
				dimensions: [640,480],
				initFill: {
					color: '0000FF',  // solid red
					opacity: 0.5
				},
				initStroke: {
					width: 5,
					color: '000000',  // solid black
					opacity: 1
				},
				initOpacity: 1,
				extPath: 'extensions/',
				extensions: ['ext-grid.js'],
				gridSnapping: true,
				gridColor: "#000",
				baseUnit: 'px',
				snappingStep: 40,
		};
		
		$.extend(curConfig, config);

		var workarea = $("#workarea");
		
		curConfig.dimensions[0] = workarea.width();
		curConfig.dimensions[1] = workarea.height()/*(docHeight - 80)*/;
		
//		_house_ = new
		_canvas_ = new floorplan.canvas.SvgCanvas(document.getElementById("svgcanvas"), curConfig);
		
		// TODO DataSource Open
		floorplan.datasource.DataSource.getInstance().open();
		/** load 하기 */
		floorplan.datasource.DataSource.getInstance().selectFloors({
			success : function(returnData) {
				var floors = returnData.floors;
				
				configFloor(floors) ;
				if (floors.length > 0) {
					floorplan.datasource.DataSource.getInstance().selectFloor(floors[((getFloorCount() != undefined && getFloorCount() != null &&  !isNaN(getFloorCount()) && getFloorCount() > 0) ? getFloorCount() - 1 : ((function(){setFloorCount(1);return 1 ;}())) - 1)].floor_id, {
						success : function(returnData) {
							floorplan.editor.getCanvas().importFloor(returnData.svg);
							// TODO 초기 세팅으로 부터 설정만 바꿈
							changeMode(config.mode);
						}
					});
				}
			}
		});
		
		updateCanvas(false);
		
		(function() {
			workarea.scroll(function() {
				// TODO:  jQuery's scrollLeft/Top() wouldn't require a null check
				if ($('#ruler_x').length != 0) {
					$('#ruler_x')[0].scrollLeft = workarea[0].scrollLeft;
				}
				if ($('#ruler_y').length != 0) {
					$('#ruler_y')[0].scrollTop = workarea[0].scrollTop;	
				}
			});
		}());
		
		importExtensions([
			floorplan.extension.UndoButton,
			floorplan.extension.RedoButton,
   			floorplan.extension.AddRoomButton,
   			floorplan.extension.DeleteRoomButton,
   			floorplan.extension.MergeRoomButton,
   			floorplan.extension.DivideRoomButton,
   			floorplan.extension.RenameRoomButton,
   			floorplan.extension.ResizeRoom,
   			floorplan.extension.MiniMap
   		]);
   		
   		window.svgEditor.connection(floorplan.editor);
   		window.svgEditor.extFunc({
   			extPath : '/smarthome/js/floorplan/svg-editor/extensions/',
   			extensions: [{js: 'ext-grid.js', id:'view_grid', callback : function() {this.buttons[0].events.click();}}]
   		});
 
   		// TODO
   		window.svgDocument = document;		// 2D.js에서 사용할 전역변수
	};
	
	
	
	function configFloor(floorInfo) {
		var numOfFloor = floorInfo.length,
			floorPlanWrap = jQuery(".floorplan-wrap"),
			floorFrame = undefined ;

		setNumOfFloor(numOfFloor) ;

		floorPlanWrap.append(makeFloorPlanHomeHtml()) ;
		
		if (currentMode() == 'editor') {
			floorPlanWrap.find('.floorplan').css('visibility', 'hidden');
		}
		
		
		for(var i = numOfFloor - 1 ; i >= 0 ; i--) {
			floorFrame = makeFloorHtml(floorInfo[i], i) ;
			jQuery('.home-floor').append(floorFrame) ;
		}
		
		attachMainFloorEvent() ;
	} ;
		
	function attachMainFloorEvent() {
		var floorList = jQuery(".home-floor dl"),
			startEvent = getStartEvent() ;
		
		floorList.unbind(startEvent).bind(startEvent, onMainFloorStartEvent) ;
	} ;
	
	function onMainFloorStartEvent(event) {	
		event.originalEvent.preventDefault() ;
		window.event.stopPropagation() ;
		setFloorCount(parseInt(jQuery(this).attr('data-floorCount')));
		window.flooridid = jQuery(this).attr("data-floorid") ;
		jQuery(".floorplan-home .selected").removeClass("selected");
		jQuery(this).addClass("selected") ;
		
		jQuery(".floorplan-room p:eq(0)").text('Floor' + ((getNumOfFloor() != undefined && getNumOfFloor() != null && !isNaN(getNumOfFloor()) && getNumOfFloor() > 1) ? (' ' + getFloorCount()) : '')) ;
		
		floorplan.datasource.DataSource.getInstance().selectFloor(jQuery(this).attr("data-floorid"), {
			success : function(returnData) {
				floorplan.editor.getCanvas().importFloor(returnData.svg) ;
				
				var roomList = jQuery("path[data-type=room]"),
					len = roomList.length,
					onPower = false,
					onLight = false ;
					//floorId = jQuery("path[data-type=floor]").attr("id") ;
			
				for(var i = 0 ; i < len ; i++) {
					var roomId = roomList.filter(":eq(" + i + ")").attr("id"),
						roomInfo = getCanvas().getRoomDataFromElement(roomId) ;
				
					if(roomInfo.poweron == "true") {
						onPower = true ;
					}
					
					if(roomInfo.lighton == "true") {
						onLight = true ;
					}
				}
			
				setFloorOnOffInfo(onLight, onPower, getFloorCount()) ;
			
				getJQfloorplanWrap().find('.floorplan-room').find('.button.lights img').attr('src', '/smarthome/images/tablet/room_lights_' + ((getFloorOnOffInfo().onLight == true) ? 'on' : 'off') + '.png') ;
				getJQfloorplanWrap().find('.floorplan-room').find('.button.power img').attr('src', '/smarthome/images/tablet/room_power_' + ((getFloorOnOffInfo().onPower == true) ? 'on' : 'off') + '.png');
			}
		});
	} ;
	
	function onMainFloorEndEvent(event) {
		event.originalEvent.preventDefault() ;
		window.event.stopPropagation() ;
		
		goToCenterThroughBBox(jQuery("path[data-type=floor]"), getTightZoomForFloor()) ;
		getJQfloorplanWrap().find(".floorplan").css("visibility", "hidden") ;
		jQuery('.editor').css("visibility", "visible") ;
		getJQfloorplanWrap().find('.floorplan-room').css('display', 'block');
	} ;

	function makeFloorHtml(floorData, index) {
		var roomCount = floorData.svg.match(/<roomdata data-id/gi) ? floorData.svg.match(/<roomdata data-id/gi).length : 0;
		var deviceCount = floorData.svg.match(/<devicedata/gi) ? floorData.svg.match(/<devicedata/gi).length : 0;
		
		var floor = "Floor" + (getNumOfFloor() > 1 ? " " + (index + 1) : ""),
			className = getFloorClass(floorData.svg),
			floorHtml = '<dl class="' + className + ((index == 0) ? " selected" : "")  + '" data-floorId="'+ floorData.floor_id + '" data-floorCount="' + (index + 1) + '">' +
							'<dd>' + floor + '<div class="icon alert off"></div></dd>' +
							'<dd><b>$13.54</b> / 18.31kWh</dd>' +
							'<dd>Device <b>' + deviceCount + '</b></dd>' +
							'<dd>Room <b>' + roomCount + '</b></dd>' +
							'<br class="clear">' +
						'</dl>' ;
		
		return floorHtml ;
	} ;
	
	function getFloorClass(data) {
		var className = "security";
		if(data.indexOf('energy-efficiency="1"') > 0) {
			className = "attention";
		} else if(data.indexOf('data-poweron="true"') > 0) {
			className = "security";
		}
		
		return className;
	};
	
	function setFloorColor() {
		var className = "";
		floorplan.datasource.DataSource.getInstance().selectFloors({
			success : function(returnData) {
				var floors = returnData.floors;
				var jQFloor = "";
				for(var i = 0, max = floors.length; max > i; i++) {
					className = getFloorClass(floors[i].svg);
					jQFloor = jQuery('.home-floor > dl[data-floorcount="' + (i + 1) + '"]');
					jQFloor.removeClass("security")
							.removeClass("attention")
							.removeClass("default")
							.addClass(className);
					
					var roomCount = floors[i].svg.match(/<roomdata data-id/gi) ? floors[i].svg.match(/<roomdata data-id/gi).length : 0;
					var deviceCount = floors[i].svg.match(/<devicedata/gi) ? floors[i].svg.match(/<devicedata/gi).length : 0;
					jQFloor.find("dd:eq(2) > b").text(deviceCount);
					jQFloor.find("dd:eq(3) > b").text(roomCount);
				}
			}
		});
	};
	
	function makeFloorPlanHomeHtml() {
		var floorPlanHomeHtml = '<div class="floorplan floorplan-home-cover" style="visibility:hidden; z-index:5; position:absolute;">' +
									'<div class="floorplan-home">' +
										'<div class="home-ground"></div>' +
										'<div class="home-roof"></div>' +
										'<div class="home-floor"></div>' +
									'</div>' +
								'</div>' ;
		
		return floorPlanHomeHtml ;
	} ;
	
	/**
	 * mode에 따라 zoom을 plus or minus 한다.
	 * 
	 * @param mode = "plus" or "minus"
	 */
	function changeZoom(mode) {
		var canvas = getCanvas(),
			zoom = canvas.getZoom(),
			maxZoom = canvas.getMaxZoom(),
			minZoom = canvas.getMinZoom(),
			zoomPool = getZoomPool(),
			nextZoomIdx = null,
			w_area = $("#workarea"),
			factor = null ;
		
		if(mode == "plus" && zoom < maxZoom) {
			nextZoomIdx = getCurrentZoomIdx() + 1 ;
			setCurrentZoomIdx(nextZoomIdx) ;
			changeZoom(zoomPool[nextZoomIdx]) ;
			return ;
		} else if(mode == "minus" && zoom > minZoom) {
			nextZoomIdx = getCurrentZoomIdx() - 1 ;
			setCurrentZoomIdx(nextZoomIdx) ;
			changeZoom(zoomPool[nextZoomIdx]) ;
			return ;
		} else if(mode == undefined) {	//go back default zoom status (default situation is zoomm == 1)
			canvas.setZoom(1) ;
			factor = 0 ;
		} else if(typeof(mode) == "number") {
			canvas.setZoom(0) ;
			factor = mode ;
		} else {
			return ;
		}

		zoomChanged(window, {
			width : 0,
			height : 0,
			// center pt of scroll position
			x : (w_area[0].scrollLeft + w_area.width()) / (zoom / maxZoom),
			y : (w_area[0].scrollTop + w_area.height()) / (zoom / maxZoom),
			factor : factor
		}, false);
		
		//grid size change
		var changedZoom = canvas.getZoom(),
			miniMap = getExtension("MiniMap").getMiniMap() ; 
		
		if(window.svgEditor.extensions.view_grid) {
			window.svgEditor.extensions.view_grid.gridSizeChange(changedZoom) ;
			
			// grid 위치 옮김
			var gridPattern = document.querySelector("pattern#gridpattern"),
				svgcontent = document.querySelector("svg#svgcontent");
			
			gridPattern.setAttribute("x", svgcontent.getAttribute("x"));
			gridPattern.setAttribute("y", svgcontent.getAttribute("y"));
		}
		miniMap.adjustNavigatorByZoom(changedZoom, getDefaultZoomIdx(), getCurrentZoomIdx()) ;
		refreshWorkAreaIScroll() ;
		
		//zoom 두배시 세부 방이름 표현.
		var initZoom = floorplan.editor.getCanvas().getInitZoom(); 
		var zoom = 1;
		
		if(initZoom == 1.5) {
			zoom = 1;
		} else if(initZoom <= 1) {
			zoom = 1.5;
		} else {
			zoom = initZoom * 1.5;
		} 
		
		if( zoom <= floorplan.editor.getCanvas().getZoom()
			|| floorplan.editor.getCanvas().getZoom() == floorplan.editor.getCanvas().getMaxZoom()){
			floorplan.editor.getCanvas().isAllRoomTitle(true);
//			floorplan.editor.getCanvas().displayRoomInfo(true);
			
		}  else if(initZoom == floorplan.editor.getCanvas().getZoom() || floorplan.editor.getCanvas().getZoom() <= 1) {
			floorplan.editor.getCanvas().isAllRoomTitle(false);
			if (document.querySelector("svg#svgcontent > g").childNodes.length > 0) {
//				floorplan.editor.getCanvas().displayRoomInfo(falCse);
			}
		}
		
		var tightZoom = getTightZoomForFloor(true);
		if(tightZoom < 1) {
			var originalViewBox = getOriginalViewBox();
			
			if (originalViewBox.width == null) {
				var svgContent = document.querySelector("svg#svgcontent"),
					newViewBoxWidth = svgContent.viewBox.animVal.width * (1 / (tightZoom - 0.1)),
					newViewBoxHeight = svgContent.viewBox.animVal.height * (1 / (tightZoom - 0.1)),
					viewBoxStr = "0 0 " + newViewBoxWidth + " " + newViewBoxHeight ;
				
				svgContent.setAttribute("viewBox", viewBoxStr) ;
				setOriginalViewBox(newViewBoxWidth, newViewBoxHeight) ;
			}
			
			var viewBoxStr = "0 0 " + getOriginalViewBox().width + " " + getOriginalViewBox().height,
				svgContent = jQuery("#svgcontent").get(0),
				mapSvgContent = jQuery("#mapSvgContent").get(0),
				svgContentScale = parseInt(svgContent.getAttribute("width")) / parseInt(mapSvgContent.getAttribute("width")) ;
			
			jQuery("#svgcontent").get(0).setAttribute("viewBox", viewBoxStr) ;
			
			if((getSvgContentPos().x != undefined) && (getSvgContentPos().y != undefined)) {
				svgContent.setAttribute("x", getSvgContentPos().x) ;
				svgContent.setAttribute("y", getSvgContentPos().y) ;
				
				mapSvgContent.setAttribute("x", getSvgContentPos().x / svgContentScale);
				mapSvgContent.setAttribute("y", getSvgContentPos().y / svgContentScale);
			}
			
			/* 2012.11.09, tight zoom 반영 후 gridPattern 변경 */
			if(window.svgEditor.extensions.view_grid) {
				window.svgEditor.extensions.view_grid.gridSizeChange(factor * (getTightZoomForFloor(true) - 0.1));
				
				// grid 위치 옮김
				var gridPattern = document.querySelector("pattern#gridpattern"),
					svgcontent = document.querySelector("svg#svgcontent");
				
				gridPattern.setAttribute("x", svgcontent.getAttribute("x"));
				gridPattern.setAttribute("y", svgcontent.getAttribute("y"));
			}
		}
		
		/* 2012.11.07, 수정 작업 */
		floorplan.editor.getCanvas().displayRoomInfo();
		
		var scroll = floorplan.editor.getWorkAreaIScroll(),
			selectedRoom = null,
			centerPoint = { x: 0, y: 0 },
			diff = {
				x: jQuery(".editor").outerWidth(true) / 2,
				y: jQuery(".editor").outerHeight(true) / 2
			};
		
		if (!selectedRoom) {
			centerPoint = {
				x: jQuery("#svgcanvas").outerWidth(true) / 2,
				y: jQuery("#svgcanvas").outerHeight(true) / 2
			};
		} else {
			var bbox = selectedRoom.getBBox();
			
			centerPoint = {
				x: bbox.x + bbox.width / 2,
				y: bbox.y + bbox.height / 2
			};
		}
		
		diff.x -= centerPoint.x;
		diff.y -= centerPoint.y;
		
		if (diff.x < scroll.maxScrollX) {
			diff.x = scroll.maxScrollX;
		} else if (diff.x > 0) {
			diff.x = 0;
		}
		if (diff.y < scroll.maxScrollY) {
			diff.y = scroll.maxScrollY;
		} else if (diff.y > 0) {
			diff.y = 0;
		}
		
		scroll.scrollTo(diff.x, diff.y, 0);
	} ;
	
	function zoomChanged(window, bbox, autoCenter) {
		var scrbar = 15,
			w_area = $("#workarea");
		
		var z_info = getCanvas().setBBoxZoom(bbox, w_area.width()-scrbar, w_area.height()-scrbar);
		if(!z_info) return;
		console.log("current_zoom : " + z_info.zoom);
		var zoomlevel = z_info.zoom,
			bb = z_info.bbox;
		
		$('#zoom').val(zoomlevel*100);
		
		if(autoCenter || bbox.autoCenter) {
			updateCanvas();
		} else {
			updateCanvas(false, {x: bb.x * zoomlevel + (bb.width * zoomlevel)/2, y: bb.y * zoomlevel + (bb.height * zoomlevel)/2});
		}

		if(getCanvas().getMode() == 'zoom' && bb.width) {
			// Go to select if a zoom box was drawn
			setSelectMode();
		}
		updateWireFrame();
	} ;
	
	function updateWireFrame() {
		// Test support
		var workarea = jQuery("#workarea");
		var rule = "#workarea.wireframe #svgcontent * { stroke-width: " + 1/getCanvas().getZoom() + "px; }";
		$('#wireframe_rules').text(workarea.hasClass('wireframe') ? rule : "");
	} ;
	
	function setSelectMode() {
		var curr = $('.tool_button_current');
		if(curr.length && curr[0].id !== 'tool_select') {
			curr.removeClass('tool_button_current').addClass('tool_button');
			$('#tool_select').addClass('tool_button_current').removeClass('tool_button');
			$('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all} #svgcanvas svg{cursor:default}');
		}
		getCanvas().setMode('select');
		workarea.css('cursor','auto');
	} ;
	
	var refreshWorkAreaIScroll = function() {
		var width = jQuery("#svgcanvas").css("width"),
			height = jQuery("#svgcanvas").css("height") ;
		
		jQuery("#workareaScroller").css("width", width) ;
		jQuery("#workareaScroller").css("height", height) ;
		
		getWorkAreaIScroll().refresh() ;
	} ;
	
	var importExtensions = function(extensions) {
		
		var extension = undefined;
		
		for (var i = 0, iLen = extensions.length ; i < iLen ; i++) {
			extension = new extensions[i]();
			
			addExtension(extension.getClassName(), extension);
		};
	};
	
	var getAbsolutePos = function (obj) {
		var position = new Object;
		position.x = 0 ;
		position.y = 0 ;

		if(obj) {
			position.x = obj.offsetLeft;
			position.y = obj.offsetTop;

			if(obj.offsetParent) {
				var parentpos = getAbsolutePos(obj.offsetParent) ;
				position.x += parentpos.x ;
				position.y += parentpos.y ;
			}
		}
		return position ;
	} ;
		
	var getTightZoomForFloor = function(isGetOriginalTightZoom) {
		var floorPath = jQuery("path[data-type=floor]").get(0),
			zoomPool = getZoomPool() ;
		
		if(floorPath == undefined) {
			return 1 ;
		}
			
		var floorBBox = floorPath.getBBox(),
			workareaWidth = jQuery(workarea).get(0).offsetWidth,
			workareaHeight = jQuery(workarea).get(0).offsetHeight,
			widthZoom = workareaWidth / floorBBox.width,
			heightZoom = workareaHeight / floorBBox.height,
			tightZoom = (widthZoom > heightZoom) ? heightZoom : widthZoom ;
		
		if(isGetOriginalTightZoom == true) {
			return tightZoom ;
		}
		
		//if(!isPhone() && !isMobileDevice()) {
			if(tightZoom > 1) {
				tightZoom = tightZoom - 0.2 ;
			}
		//}

		for(var i = 0, len = zoomPool.length ; i < len - 1 ; i++) {
			if((tightZoom >= zoomPool[i]) && (tightZoom < zoomPool[i + 1])) {
				tightZoom = zoomPool[i] ;
			}
		}
				
		floorplan.editor.getCanvas().setInitZoom(tightZoom);
		return tightZoom ;
	} ;
	
	/**
	 * @type goToCenterThroughBBox
	 * @param path   (화면 중앙에 올 path(이 path의 bBox를 구함))
	 * @param zoom   (화면의 zoom은 몇으로 할 것인지)
	 */
	
	function goToCenterThroughBBox(path, zoom) {
		var svgContent = jQuery("#svgcontent").get(0),
			workArea = jQuery(workarea).get(0),
			workAreaTop = floorplan.editor.getAbsolutePos(workArea).y,
			mapSvgContent = jQuery("#mapSvgContent").get(0),
			svgContentScale = parseInt(svgContent.getAttribute("width")) / parseInt(mapSvgContent.getAttribute("width")) ;
		
		zoom = (zoom < 1) ? 1 : zoom ; 
		changeZoom(zoom) ;
		floorplan.editor.updateCanvas() ;
		moveTobBoxCenter(path, zoom) ;
		setCurrentZoomIdx(getZoomIdx(zoom)) ;
		setDefaultZoomIdx(getZoomIdx(zoom)) ;
		
		if(getTightZoomForFloor(true) < 1) {
			var newViewBoxWidth = svgContent.viewBox.animVal.width * (1 / (getTightZoomForFloor(true) - 0.1)),
				newViewBoxHeight = svgContent.viewBox.animVal.height * (1 / (getTightZoomForFloor(true) - 0.1)),
				viewBoxStr = "0 0 " + newViewBoxWidth + " " + newViewBoxHeight ;
			
			svgContent.setAttribute("viewBox", viewBoxStr) ;
			setOriginalViewBox(newViewBoxWidth, newViewBoxHeight) ;
			
			var rect = svgContent.getBoundingClientRect(),
				x = ((workArea.offsetWidth - rect.width) / 2) - (Number(document.querySelector(".editor").style.left.split("px")[0]) - rect.left), //도형의 left - editor의 left
				//x = ((workArea.offsetWidth - rect.width) / 2) - rect.left,
				y = ((workArea.offsetHeight - rect.height) / 2) - (rect.top - workAreaTop) ;
			
			setSvgContentPos(x, y) ;
			
			svgContent.setAttribute("x", getSvgContentPos().x) ;
			svgContent.setAttribute("y", getSvgContentPos().y) ;
			
			mapSvgContent.setAttribute("x", getSvgContentPos().x / svgContentScale) ;
			mapSvgContent.setAttribute("y", getSvgContentPos().y / svgContentScale) ;
			
			/* 2012.11.09, tight zoom 반영 후 gridPattern 변경 */
			if(window.svgEditor.extensions.view_grid) {
				window.svgEditor.extensions.view_grid.gridSizeChange(zoom * (getTightZoomForFloor(true) - 0.1));
				
				// grid 위치 옮김
				var gridPattern = document.querySelector("pattern#gridpattern"),
					svgcontent = document.querySelector("svg#svgcontent");
				
				gridPattern.setAttribute("x", svgcontent.getAttribute("x"));
				gridPattern.setAttribute("y", svgcontent.getAttribute("y"));
			}
		}
		
		floorplan.editor.getCanvas().displayRoomInfo();
		
		return zoom ;
	} ;
	
	function moveTobBoxCenter(path, zoom) {
		var bBox = path.get(0).getBBox(),
			xPos = bBox.x + (bBox.width / 2),
			yPos = bBox.y + (bBox.height / 2) ;
	
		moveIScroll(xPos, yPos, zoom) ;
	} ;
	
	/**
	 * @type moveIScroll
	 * @param xPos
	 * @param yPos (xPos와 yPos가 화면의 중앙이 되도록 iscroll이 움직인다.)
	 * @param zoom iscroll이 scroll될 화면의 zoom정도.
	 */
	
	function moveIScroll(xPos, yPos, zoom) {
		var workAreaIScroll = getWorkAreaIScroll(),
			scrollXPos = null,
			scrollYPos = null ;
		
		if((xPos == undefined) && (yPos == undefined)) {	//moveToCenter route
			scrollXPos = (((workAreaIScroll.scrollerW - workAreaIScroll.wrapperW) / 2) * -1),
			scrollYPos = (((workAreaIScroll.scrollerH - workAreaIScroll.wrapperH) / 2) * -1) ;
		} else {//moveTo(x,y) position route 
			scrollXPos = ((xPos * zoom) - (workAreaIScroll.wrapperW / 2)),
			scrollYPos = ((yPos * zoom) - (workAreaIScroll.wrapperH / 2)) ;
			
			if(scrollXPos < 0) {
				scrollXPos = 0 ;
			}
			
			if(scrollYPos < 0) {
				scrollYPos = 0 ;
			}
			
			if((scrollXPos + workAreaIScroll.wrapperW) >= workAreaIScroll.scrollerW) {
				scrollXPos = workAreaIScroll.scrollerW - workAreaIScroll.wrapperW ;
			}
			
			if((scrollYPos + workAreaIScroll.wrapperH) >= workAreaIScroll.scrollerH) {
				scrollYPos = workAreaIScroll.scrollerH - workAreaIScroll.wrapperH ;
			}
			
			scrollXPos = (scrollXPos * -1) ;
			scrollYPos = (scrollYPos * -1) ;
		}
		
		workAreaIScroll.scrollTo(scrollXPos, scrollYPos) ;
	} ;

	function getZoomIdx(zoom) {
		var zoomPool = getZoomPool(),
			idx = 0 ;
		
		for(var i = 0, len = zoomPool.length ; i < len ; i++) {
			if(zoom == zoomPool[i]) {
				idx = i ;
				break ;
			}
		}
		
		return idx ;
	} ;
	/**
	 * Export
	 */
	(!window.floorplan) && (window.floorplan = {});
	(!window.floorplan.editor) && (window.floorplan.editor = {});
	
	window.floorplan.editor.curConfig = curConfig;
	window.floorplan.editor.getFloorCount = getFloorCount;
	window.floorplan.editor.setFloorCount = setFloorCount;
	window.floorplan.editor.getCanvas = getCanvas;
	window.floorplan.editor.getWorkAreaIScroll = getWorkAreaIScroll;
	window.floorplan.editor.init = init;
	window.floorplan.editor.importExtensions = importExtensions;
	window.floorplan.editor.getExtension = getExtension;
	window.floorplan.editor.addExtension = addExtension;
	window.floorplan.editor.execExtension = execExtension;
	window.floorplan.editor.getDefaultWork = getDefaultWork;
	window.floorplan.editor.currentWork = currentWork;
	window.floorplan.editor.changeWork = changeWork;
	window.floorplan.editor.showMessage = showMessage;
	window.floorplan.editor.currentMode = currentMode;
	window.floorplan.editor.changeMode = changeMode;
	window.floorplan.editor.getJQfloorplanWrap = getJQfloorplanWrap;
	window.floorplan.editor.updateCanvas = updateCanvas;
	window.floorplan.editor.refreshWorkAreaIScroll = refreshWorkAreaIScroll ;
	window.floorplan.editor.getAbsolutePos = getAbsolutePos ;
	window.floorplan.editor.changeZoom = changeZoom ;
	window.floorplan.editor.zoomChanged = zoomChanged ;
	window.floorplan.editor.updateWireFrame = updateWireFrame ;
	window.floorplan.editor.setSelectMode = setSelectMode ;
	window.floorplan.editor.getTightZoomForFloor = getTightZoomForFloor ;
	window.floorplan.editor.getZoomPool = getZoomPool ;
	window.floorplan.editor.setOriginalViewBox = setOriginalViewBox ;
	window.floorplan.editor.setSvgContentPos = setSvgContentPos ;
	window.floorplan.editor.getCurrentZoomIdx = getCurrentZoomIdx ;
	window.floorplan.editor.getDefaultZoomIdx = getDefaultZoomIdx ;
	window.floorplan.editor.setDefaultZoomIdx = setDefaultZoomIdx ;
	window.floorplan.editor.getFloorOnOffInfo = getFloorOnOffInfo ;
	window.floorplan.editor.clearFloor = clearFloor ;
	
	return {
		floorplan : {
			editor : {
				curConfig : curConfig,
				getFloorCount : getFloorCount,
				setFloorCount : setFloorCount,
				getCanvas : getCanvas,
				init : init,
				importExtensions : importExtensions,
				getExtension : getExtension,
				addExtension : addExtension,
				execExtension : execExtension,
				getDefaultWork : getDefaultWork,
				currentWork : currentWork,
				changeWork : changeWork,
				currentMode : currentMode,
				changeMode : changeMode,
				getJQfloorplanWrap : getJQfloorplanWrap,
				updateCanvas : updateCanvas,
				getWorkAreaIScroll : getWorkAreaIScroll,
				refreshWorkAreaIScroll : refreshWorkAreaIScroll,
				getAbsolutePos : getAbsolutePos,
				changeZoom : changeZoom,
				zoomChanged : zoomChanged,
				updateWireFrame : updateWireFrame,
				setSelectMode : setSelectMode,
				getTightZoomForFloor : getTightZoomForFloor,
				getZoomPool : getZoomPool,
				setOriginalViewBox : setOriginalViewBox,
				setSvgContentPos : setSvgContentPos,
				getCurrentZoomIdx : getCurrentZoomIdx,
				getDefaultZoomIdx : getDefaultZoomIdx,
				setDefaultZoomIdx : setDefaultZoomIdx,
				getFloorOnOffInfo : getFloorOnOffInfo,
				
			}
		}
	};
	
}(this)); 

jQuery(window).bind("resize", function() {
	floorplan.editor.updateCanvas(false);
});

